import jwt from 'jsonwebtoken'
import { JWT, NODE_ENV } from '../config/constant'
import crypto from 'crypto'
import { NodeSSH } from 'node-ssh'
import dayjs from 'dayjs'
import fs from 'fs'
/**
 * @description ssh连接
 * @param src 本地文件路径
 * @param des 目标服务器文件路径
 * @param options
 */
export const sshConnect = (
  src: string,
  des: string,
  options: { callback?: Function; directory?: boolean }
) => {
  const ssh = new NodeSSH()
  ssh
    .connect({
      host: '42.193.231.115',
      port: 22,
      username: 'root',
      privateKey: fs.readFileSync('C:\\Users\\Administrator\\.ssh\\id_rsa').toString()
    })
    .then(() => {
      const methods = options?.directory ? 'putDirectory' : 'putFile'
      ssh[methods](src, des)
        .then(() => {
          console.log('文件上传成功')
        })
        .catch((e: Error) => {
          console.log('文上传失败：', e)
        })
        .finally(() => ssh.dispose())
      options?.callback?.()
    })
    .catch((e: Error) => {
      console.log('ssh连接失败：', e)
    })
}

/**
 * @description 获取客户端IP地址
 * @param ctx
 */
export const getClientIpAddress = (ctx: any) => {
  const headers = ctx.headers
  if (headers['x-forwarded-for']) {
    const ipList = headers['x-forwarded-for'].split(',')
    return ipList[0]
  }

  return '0.0.0.0'
}

/**
 * @description 解析token
 * @param token
 * @returns userId
 */
export const decodeToken = (token: string) => {
  let jwtInfo = jwt.verify(token, JWT[NODE_ENV].secret) as any
  try {
    return jwtInfo.userId
  } catch (err) {
    return 'token不合法'
  }
}

/**
 * @description 生成token
 * @param userId
 */
export const generatorToken = (userId: string) => {
  return jwt.sign({ userId }, JWT[NODE_ENV].secret, { expiresIn: JWT[NODE_ENV].expiresIn })
}

/**
 * @description 判断是否为邮箱
 * @param email 邮箱地址
 */
export const validateEmail = (email: string) => {
  const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
  return reg.test(email)
}

/**
 * @description 判断是否为手机号
 * @param mobile 手机号
 */
export const validateMobile = (mobile: string) => {
  const reg = /^[1][3,4,5,7,8][0-9]{9}$/
  return reg.test(mobile)
}

/**
 * @description 生成随机长度字符串
 * @param len 随机长度
 */
export const createRandomString = (len = 16) => {
  const t = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  const a = t.length
  let n = ''
  for (let i = 0; i < len; i++) n += t.charAt(Math.floor(Math.random() * a))
  return n
}

/**
 * @description 256加密
 * @param str 加密字符串
 */
export const encodeCrypto256 = (str: string) => {
  // 创建hash对象
  const hash = crypto.createHash('sha256').update(str)
  // 生成hash值
  const passwordHash = hash.digest('hex')
  return passwordHash
}
/**
 * @description 256解密
 * @param str 解密字符串
 */
export const decodeCrypto256 = (str: string) => {
  // 创建hash对象
  const hash = crypto.createHash('sha256').update(str)
  // 生成hash值
  const passwordHash = hash.digest('hex')
  return passwordHash
}

/**
 * @description im日期格式
 * @param datetime 时间戳
 * @returns im日期格式字符串
 */
export const showDayTime = (datetime: number) => {
  if (!datetime) return ''
  const weeks = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  // 当天 显示时分
  if (dayjs().isSame(datetime, 'day')) {
    return dayjs(datetime).format('HH:mm')
  }
  // 昨天 昨天+时分
  if (dayjs().startOf('day').subtract(1, 'day').isSame(datetime, 'day')) {
    return `昨天 ${dayjs(datetime).format('HH:mm')}`
  }
  // 本周 显示周几+时分
  if (dayjs().isSame(datetime, 'week')) {
    const weekIndex = dayjs().day()
    return `${weeks[weekIndex]} ${dayjs(datetime).format('HH:mm')}`
  }
  // 本年，显示月-日
  if (dayjs().isSame(datetime, 'year')) {
    return dayjs(datetime).format('MM-DD')
  }
  // 本年之前 显示年月日
  if (dayjs(datetime).isAfter(new Date(), 'year')) {
    return dayjs(datetime).format('YYYY-MM-DD')
  }
}

/**
 * @description 根据文件类型
 * @param fileName 文件路径
 * @return 文件类型
 */
export function getFileType(fileName: string): string {
	const image = ["png", "jpg", "jpeg", "svg", "webp", "jpeg", "bmp", "gif"];
	const txt = ["txt"];
	const xls = ["xls", "xlsx"];
	const docx = ["doc", "docx"];
	const pdf = ["pdf"];
	const ppt = ["ppt", "pptx"];
	const video = ["mp4", "flv", "mkv"];
	const audio = ["mp3", "wav", "wmv"];
	const zip = ["zip", "tar", "7z"];
	const json = ["json"];
	const html = ["html"];
	const css = ["css"];
	const js = ["js"];
	const allType = { image, txt, xls, docx, pdf, ppt, video, audio, zip, json, html, css, js } as any;

	//获取后缀
	const ext = fileName.slice(fileName.lastIndexOf(".") + 1);
	for (const key in allType) {
		if (allType[key].includes(ext)) {
			return key;
		}
	}
	return "unknown";
}
/**
 * @description 模拟sleep
 * @param ms 毫秒
 * @returns 
 */
export function sleep(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
